<template>
  <div class="container">
    <van-cell-group>
      <single-picker
        label="分类"
        :value="formData.category_id"
        :data="categorys"
        required
        content-column="name"
        value-column="id"
        placeholder="请选择分类"
        :error="error.category_id"
        @change="onCheckedCategory"
      />
    </van-cell-group>
    <van-cell-group>
      <van-field
        :value="formData.title"
        input-align="right"
        clearable
        required
        label="标题"
        id="title"
        placeholder="请输入标题内容，不可超过50字"
        :error="error.title"
        @change="onChangeInput"
      />
    </van-cell-group>
    <van-cell-group custom-class="textarea-cell">
      <van-field
        :value="formData.content"
        type="textarea"
        required
        label="内容"
        placeholder="请输入内容描述，不可超过1000字"
        id="content"
        :error="error.content"
        :autosize="textareaOption"
        @change="onChangeInput"
      />
    </van-cell-group>
    <van-cell-group>
      <van-cell
        title="图片"
        value="可上传多张图片内容"
      />
      <div class="images-upload">
        <van-uploader
          name="images"
          :file-list="imageList"
          :max-count="10"
          multiple
          image-fit="aspectFill"
          @afterRead="onAfterReadFiles"
          @delete="onDeleteImage"
        />
      </div>
    </van-cell-group>
    <van-cell-group>
      <van-cell
        title="附件"
        title-width="80px"
        custom-class="file-upload"
      >
        <van-uploader
          name="attach"
          accept="file"
          :file-list="attachs"
          :max-count="1"
          @afterRead="onAfterRead"
          @delete="onDeleteAttach"
        >
          <van-button
            icon="plus"
            type="primary"
            size="small"
          >上传文件</van-button>
        </van-uploader>
      </van-cell>
    </van-cell-group>

    <div class="form-action">
      <van-button
        type="info"
        round
        @click="onSubmit"
      >发布</van-button>
    </div>
  </div>
</template>

<script>
import SinglePicker from '@/components/form/singlePicker'
import { attachUpload } from '@/api'
export default {
  components: {
    SinglePicker
  },

  data () {
    return {
      categorys: [
        { name: '能源', id: 1 },
        { name: '计算机', id: 2 },
        { name: '生物科技', id: 3 },
        { name: '海洋', id: 4 },
        { name: '医疗健康', id: 5 },
        { name: '教育', id: 6 },
        { name: '金融', id: 7 }
      ],
      error: {
        title: false,
        category_id: false,
        content: false
      },
      validateRules: [
        {
          name: 'title',
          required: true,
          error: false
        },
        {
          name: 'category_id',
          required: true,
          error: false
        },
        {
          name: 'content',
          required: true,
          error: false
        }
      ],
      multiUpload: true,
      imageList: [],
      attachs: [],
      id: 0,
      textareaOption: {
        maxHeight: 150,
        minHeight: 100
      },
      formData: {
        title: '',
        category_id: '',
        content: '',
        images: []
      },
      title: '导航栏',
      titleColor: '#000000',
      value: ''
    }
  },
  onLoad (option) {
    this.id = option.id
    console.log(option)
    console.log('小程序 [page-blog] 生命周期: onLoad: 监听页面加载')
  },
  // 跳转后页面
  mounted () {
    console.log(this.id)
  },
  watch: {
    imageList: {
      handler (now, old) {
        let arrnew = now.map(obj => {
          return obj.path
        })
        this.formData.images = arrnew
        console.log(arrnew)
      },
      deep: true,
      immediate: true
    },
    formData: {
      handler (now, old) {
        console.log('当前表单数据', now)
      },
      deep: true,
      immediate: true
    }
  },
  created () {
    console.log('entryform created')
  },
  methods: {
    async onAsyncUpload (file) {
      try {
        let res = await attachUpload(file)
        return { ...file, url: res.url, path: res.path }
      } catch (e) {
        console.log(e)
        return null
      }
    },
    onBeforeRead (e) {
      const { file, callback } = e.mp.detail
      console.log(file)
      if (file.type === 'image') {
        const isImage = true
        callback(isImage)
      } else {
        const isImage = false
        console.log(callback)
        callback(isImage)
      }
    },
    onDeleteImage (e) {
      console.log(e)
      const { index } = e.mp.detail
      this.imageList.splice(index, 1)
    },
    onDeleteAttach (e) {
      console.log(e)
      const { index } = e.mp.detail
      this.attachs.splice(index, 1)
    },
    onAfterReadFiles (e) {
      const { file, name } = e.mp.detail
      console.log(name)
      console.log(file)
      const fileList = this.imageList
      if (Array.isArray(file)) {
        for (let i = 0; i < file.length; i++) {
          this.onUpload(file[i], this.imageList)
        }
      } else {
        this.onUpload(file, fileList)
      }
      console.log('upload res:', this.imageList)
    },
    onAfterRead (e) {
      const { file, name } = e.mp.detail
      console.log('onAfterRead name:', name)
      console.log('onAfterRead file:', file)
      this.onUpload(file, this.attachs, 'file')
    },
    onUpload (file, list, type = 'image') {
      console.log('onUpload>>>>>>>>>', file)
      return attachUpload(file, type).then(res => {
        list.push({
          ...file,
          url: res.url,
          path: res.path
        })
      }).catch(e => {
        console.log(e)
        list.push({
          ...file,
          status: 'failed',
          message: '上传失败'
        })
      })
    },
    onChecked (data) {
      let country = data.pop()
      this.formData.country = country.data
    },
    onChangeInput (e) {
      console.log(e)
      let id = e.mp.target.id
      let ids = id.split('.')
      console.log(ids)
      let key = ids.pop()
      let obj = this.formData
      for (let i = 0; i < ids.length; i++) {
        obj = obj[ids[i]]
      }
      this.$set(obj, key, e.mp.detail)
    },
    onCheckedCategory (data) {
      console.log('选择的分类', data)
      this.formData.category_id = data
    },
    onSuccess: function (res) {
      console.log(res.detail)
    },
    onFail: function (res) {
      console.log(res)
    },
    onSubmit () {
      for (let i = 0; i < this.validateRules.length; i++) {
        const column = this.validateRules[i]
        if (column.required && !this.formData[column.name]) {
          this.error[column.name] = true
        } else {
          this.error[column.name] = false
        }
      }
      console.log(this.error)
    }
  }
}
</script>

<style lang="less">
.search-warp {
  text-align: center;
  margin-top: 100px;
}
.container {
  background: #f4f5f9;
  padding-top: 10px;
  .van-cell {
    &-group {
      margin-bottom: 10px;
      background: #fff;
      &__title {
        padding: 20px 15px 10px !important;
      }
    }
  }
  .textarea-cell {
    .van-cell {
      flex-direction: column;
      &__value {
        margin-top: 10px;
      }
    }
  }
}
.images-upload {
  padding: 10px 15px;
}
.form-action {
  display: flex;
  align-items: center;
  justify-content: center;
  .van-button {
    padding: 0 20px;
  }
}

.file-upload {
  .van-uploader {
    &__file-icon {
      font-size: inherit !important;
    }
    &__preview {
      &-delete,
      &-delete:after {
        position: initial !important;
      }
    }
  }
  .uploader-index {
    &--van-uploader {
      display: flex;
      justify-content: flex-end;

      &__mask {
        flex-direction: row;
        background: #fff;
        color: #ff6600;
        &-icon {
          font-size: inherit;
        }
        &-message {
          margin: 0;
          padding: 0 3px;
        }
      }
      &__file {
        width: auto !important;
        height: auto !important;
        max-width: 95%;
        flex-direction: row;
        background: transparent;
        &-name {
          margin: 0;
        }
      }

      &__wrapper {
        max-width: 100%;
      }
      &__preview {
        display: flex;
        align-items: center;
        justify-content: flex-end;
        margin: 0;
        max-width: 100%;
        &-delete {
          display: flex;
          align-items: center;
          justify-content: center;
          padding: 0;
          &::after {
            display: none;
          }
          &-icon {
            display: initial;
            top: auto;
            right: auto;
            color: #000;
            transform: none;
          }
        }
      }
    }
  }
}
</style>
